#include "unp.h"



mqd_t mqd;
void  *buff;
struct mq_attr attr;
struct sigevent sigev;

static void notify_thread(union sigval);

int main(int argc,char *argv[])
{
   //int rc = -1;
   mqd = mq_open(argv[1],O_RDONLY | O_NONBLOCK);
   if(mqd == -1)
     err_sys("mq_open error");
   if(mq_getattr(mqd,&attr) == -1)
     err_sys("mq_getattr error");
 
   buff = malloc(attr.mq_msgsize);

   sigev.sigev_notify=SIGEV_THREAD;
   sigev.sigev_value.sival_ptr =NULL;
   sigev.sigev_notify_function = notify_thread;
   sigev.sigev_notify_attributes = NULL;
   if(mq_notify(mqd,&sigev) ==-1)
     err_sys("mq_notify error");

   for(;;)
     pause();
   exit(0);
}

static void notify_thread(union sigval arg){
   ssize_t n;
   u_int32_t prio;
   printf("sig_usr1 begin\n");
   if(mq_notify(mqd,&sigev) ==-1)
     err_sys("mq_notify error");
   while((n=mq_receive(mqd,buff,attr.mq_msgsize,&prio)) !=-1){
      printf("SIGUSR1 received, read %ld bytes\n",(long)n);
   }
   //if(n==-1 || n == 0)
      printf("SIGUSR1 received, no element %ld\n",(long)n);
   pthread_exit(NULL);
}
